from html import escape

from django.shortcuts import render, redirect
from .models import Note


# 装饰器
def login_check(fn):
    def wrap(request, *args, **kwargs):
        if 'uname' not in request.session and 'uid' not in request.session:
            return redirect('/')
        return fn(request, *args, **kwargs)

    return wrap


# Create your views here.
@login_check
def list_view(request):
    uname = request.session.get('uname')
    uid = request.session.get('uid')
    notes = Note.objects.filter(user_id=uid)
    return render(request, 'note/list_note.html', locals())


@login_check
def add_view(request):
    if request.method == 'GET':
        return render(request, 'note/add_note.html')
    elif request.method == 'POST':
        uid = request.session.get('uid')
        title = request.POST.get('title')
        content = request.POST.get('content')
        content = escape(content)  # 转义操作
        Note.objects.create(title=title, content=content, user_id=uid)
        return redirect('/note/')


@login_check
def mod_view(request,id):
    note = Note.objects.get(id=id)
    if request.method == 'GET':
        return render(request, 'note/mod_note.html/', locals())
    elif request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')
        note.title = title
        note.content = content
        note.save()
        return redirect('/note/')


@login_check
def del_view(request,id):
    note = Note.objects.get(id=id)
    note.delete()
    return redirect('/note/')